import CustomTextArea from '@/components/antd-comp/input/CustomTextArea'
import { PlusOutlined } from '@ant-design/icons'
import { Dropdown } from 'antd'
import { useEffect, useState } from 'react'
import './index.less'

/*

list    select数据
title   标题
value   input的值
saveFun 实时获取参数

 const list = [
    {
      key: '2',
      label: '开始',
      children: [
        {
          key: '2-1',
          label: 'create_time'
        },
        {
          key: '2-2',
          label: 'history'
        }
      ]
    }
  ] as any
  const value = ''
  const saveFun = e => {
    console.log(e, '===')
  }
  <NodeSelection list={list} value={value} saveFun={saveFun}></NodeSelection>
*/

export default function NodeSelection({ list = [] as any, title = '变量输入', value = '', saveFun }: any) {
  /* input=value */
  const [textValue, setTextValue] = useState('')
  /* select 下拉数据 */
  const [items, setItems] = useState([]) as any
  /* 光标 当前选中的 */
  const [selectedKey, setSelectedKey] = useState<string | null>(null)

  useEffect(() => {
    setItems(list)
    setTextValue(value)
  }, [list, value])

  // 查找对应 key 的 label
  const findLabelByKey = (items, key) => {
    for (const item of items) {
      if (item.key === key) {
        return item.label
      }
      if (item.children) {
        const result = findLabelByKey(item.children, key)
        if (result) {
          return result
        }
      }
    }
    return null
  }

  // 插入文本到当前光标位置
  const insertTextAtCursor = (text: string, cursorPosition: number) => {
    const newValue = textValue.slice(0, cursorPosition) + text + textValue.slice(cursorPosition)
    setTextValue(newValue)
    saveFun(newValue)
    return cursorPosition + text.length // 返回新光标位置
  }

  const onClick = ({ key }: { key: string }) => {
    const label = findLabelByKey(items, key)
    if (label) {
      // 获取光标位置并插入文本
      const textarea = document.querySelector('textarea') as HTMLTextAreaElement
      const cursorPosition = textarea?.selectionStart || 0
      const newCursorPosition = insertTextAtCursor(`{{${label}}}`, cursorPosition)
      // 更新光标位置
      if (textarea) {
        textarea.focus()
        textarea.setSelectionRange(newCursorPosition, newCursorPosition)
      }
      setSelectedKey(key)
      setTimeout(() => setSelectedKey(null), 0) // 清除选中状态
      saveFun(textValue)
    }
  }

  return (
    <div className="nodeSeleCase nodrag relative mt-2 flex w-full flex-col rounded-md border border-input bg-search-input text-sm shadow-sm">
      <div className="headCase flex h-[36px] justify-between gap-1 border-b px-2">
        <span className="bisheng-label text-xs font-medium peer-disabled:cursor-not-allowed peer-disabled:opacity-70">
          {title}
        </span>
        {/* 下拉选择 */}
        <Dropdown
          menu={{
            items,
            onClick,
            selectable: true,
            selectedKeys: selectedKey !== null ? [selectedKey] : []
          }}
        >
          <PlusOutlined className="cursonCase" />
        </Dropdown>
      </div>
      {/* input文本内容 */}
      <div className="w-[100%]">
        <CustomTextArea
          value={textValue}
          onChange={e => {
            setTextValue(e.target.value)
            saveFun(e.target.value)
          }}
          // placeholder="xxx"
          rows={4}
        ></CustomTextArea>
      </div>
    </div>
  )
}
